<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-fill-left.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="JVM," />





  <link rel="alternate" href="/atom.xml" title="我的笔记本" type="application/atom+xml" />






<meta name="description" content="导读在Java代码中，类型的加载、链接与初始化过程都是程序运行期间完成的。类加载给程序提供了更大的灵活性。">
<meta property="og:type" content="article">
<meta property="og:title" content="JVM类加载器">
<meta property="og:url" content="https://sakebow.github.io/2020/02/06/Java/JVM/JVM%E7%B1%BB%E5%8A%A0%E8%BD%BD%E5%99%A8/index.html">
<meta property="og:site_name" content="我的笔记本">
<meta property="og:description" content="导读在Java代码中，类型的加载、链接与初始化过程都是程序运行期间完成的。类加载给程序提供了更大的灵活性。">
<meta property="article:published_time" content="2020-02-06T08:07:00.000Z">
<meta property="article:modified_time" content="2020-11-21T13:33:08.944Z">
<meta property="article:author" content="sakebow">
<meta property="article:tag" content="JVM">
<meta name="twitter:card" content="summary">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":true,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://sakebow.github.io/2020/02/06/Java/JVM/JVM类加载器/"/>



<meta name="google-site-verification" content="gmKmVpWaqN85ipDFNNCd2AweYJjcTFrVxCKCy36wueo" />
<script>
var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?1d2c90caa02c073d8ebaa116ab3027fb";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script>


  <title>JVM类加载器 | 我的笔记本</title>
  








  
  <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
  <script type="text/javascript" src="/js/src/custom.js"></script>
  
<meta name="generator" content="Hexo 4.2.1"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
	
	<a href="https://github.com/sakebow" target="_blank" rel="noopener" class="github-corner" aria-label="View source on GitHub">
	  <svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"
	    style="fill:#64CEAA; color:#fff; position: fixed; top: 0; border: 0; right: 0; z-index: 999;">
	    <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
		<path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
		  fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
		<path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
		  fill="currentColor" class="octo-body"></path>
	  </svg>
	</a>
	<style>
	  .github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}
	  @keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}
	  @media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}
	</style>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">我的笔记本</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">一只干什么都会失败但是很不想放弃的科研狗</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://sakebow.github.io/2020/02/06/Java/JVM/JVM%E7%B1%BB%E5%8A%A0%E8%BD%BD%E5%99%A8/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="sakebow">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/icon/UN.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="我的笔记本">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">JVM类加载器</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-02-06T16:07:00+08:00">
                2020-02-06
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/java/" itemprop="url" rel="index">
                    <span itemprop="name">java</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2020/02/06/Java/JVM/JVM%E7%B1%BB%E5%8A%A0%E8%BD%BD%E5%99%A8/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count gitment-comments-count" data-xid="/2020/02/06/Java/JVM/JVM%E7%B1%BB%E5%8A%A0%E8%BD%BD%E5%99%A8/" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  1.9k字
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  6分钟
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="导读"><a href="#导读" class="headerlink" title="导读"></a>导读</h2><p><strong>在Java代码中，类型的加载、链接与初始化过程都是程序运行期间完成的。类加载给程序提供了更大的灵活性。</strong></p>
<a id="more"></a>
<h2 id="导读的解读"><a href="#导读的解读" class="headerlink" title="导读的解读"></a>导读的解读</h2><ul>
<li><p>运行的时候，我们往往就是直接点击编译器的运行按钮；而C、C++则是先点击编译，再点击运行。所以类似C、C++这类语言就是在程序运行之前的编译期间完成，而Java则是在运行期间完成。</p>
</li>
<li><p>这里的类型是特指一些类，而不是对象，比如我们一开始所写的public class HelloWorld，这个HelloWorld就是这里所指的类<strong>其中一种情况</strong>。</p>
</li>
<li><p>还有一种情况就是<strong>动态代理</strong>。在动态代理中获得生成类的增强类，也会加载、链接、初始化。</p>
</li>
</ul>
<h2 id="类加载器深入剖析"><a href="#类加载器深入剖析" class="headerlink" title="类加载器深入剖析"></a>类加载器深入剖析</h2><p>顾名思义，类加载器就是<strong>用于加载类的工具</strong>。首先先来了解一下Java虚拟机的结束时间。</p>
<h3 id="Java虚拟机结束生命周期的时机"><a href="#Java虚拟机结束生命周期的时机" class="headerlink" title="Java虚拟机结束生命周期的时机"></a>Java虚拟机结束生命周期的时机</h3><ul>
<li><p>执行了System.exit()方法</p>
</li>
<li><p>程序正常执行结束</p>
</li>
<li><p>程序在执行过程中遇到了异常或错误而终止</p>
<blockquote>
<p><em>异常或错误会被Java虚拟机在当前位置一直向上抛出。但是如果没有什么机制接住异常的话，将会一直抛出到main方法中，最后因为无法处理而终止。</em></p>
</blockquote>
</li>
<li><p>由于操作系统出现错误而导致Java虚拟机进程终止 <em>（不可控，所以不展开讨论）</em></p>
</li>
</ul>
<h3 id="加载"><a href="#加载" class="headerlink" title="加载"></a>加载</h3><p>类的加载过程是“查找并加载类的二进制数据”，也就是<strong>生成字节码</strong>，并将字节码<strong>放入内存中</strong>。</p>
<p>jdk<strong>1.7</strong>以及以前的版本会将这些放入<strong>运行时数据区的方法区</strong>内，而jdk8添加了<strong>原空间</strong>来存放这些字节码。接着在内存中创建<strong>唯一一个java.lang.Class对象</strong>用于<strong>封装方法区内的数据结构</strong>。</p>
<p><strong>这正是反射机制的源头</strong>。不觉得“是什么”慢慢填补了之后“为什么”也就迎刃而解了吗？</p>
<p>但是规范中并没有规定这些Class对象应该位于哪里，Oracle的HotSpot虚拟机导师把这些放在了方法区内。这倒不是什么重点。</p>
<p>虽说这些字节码是编译器自动生成的，但是这些字节码可以被人为修改，所以在链接之前将会在<strong>后续阶段</strong>中好好地验证一遍。</p>
<h3 id="链接"><a href="#链接" class="headerlink" title="链接"></a>链接</h3><ul>
<li><p>验证：确保被加载类的正确性（验证字节码）</p>
</li>
<li><p>准备：为类的<strong>静态变量</strong>分配内存，将其初始化为默认值。</p>
<blockquote>
<p>需要强调的是，这里的默认值是编译器定义的默认值。也就是说，在加载这个类的时候，将会给类内的静态变量分配一个内存空间，而这个变量立马就被规定为默认值。比如int类型将会获得数字“0”等等。</p>
</blockquote>
</li>
<li><p>解析：将类中的<strong>符号引用</strong>转换为<strong>直接引用</strong>。</p>
</li>
</ul>
<h3 id="初始化"><a href="#初始化" class="headerlink" title="初始化"></a>初始化</h3><p>在连接完成后，为类的静态变量<strong>赋予正确的初始值</strong>。举个例子：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">int</span> a = <span class="number">1</span>;</span><br></pre></td></tr></table></figure>
<p>链接阶段的准备工作，a被赋予了数字“0”，但是在连接完成后的初始化阶段中，将会重新将a赋值为“1”。</p>
<h3 id="使用"><a href="#使用" class="headerlink" title="使用"></a>使用</h3><p>也就是正常的调用等等操作，包括访问、修改和删除等等。</p>
<h3 id="卸载"><a href="#卸载" class="headerlink" title="卸载"></a>卸载</h3><p>将类的字节码从内存中删除，这样就不能继续使用这个类了，需要时可以重新加载到内存中。平时使用场景非常少。</p>
<h2 id="Java程序对类的使用方式"><a href="#Java程序对类的使用方式" class="headerlink" title="Java程序对类的使用方式"></a>Java程序对类的使用方式</h2><p>使用方式可以分为两种，<strong>主动使用</strong>和<strong>被动使用</strong>。</p>
<p>所有的Java虚拟机实现必须在每个类或接口被程序“<strong>首次主动使用</strong>”时才初始化他们。</p>
<p>而什么是“首次主动使用”？就是<strong>只有在第一次主动使用</strong>的时候初始化。</p>
<h3 id="主动使用"><a href="#主动使用" class="headerlink" title="主动使用"></a>主动使用</h3><ul>
<li><p>创建类的实例（<code>new</code>）</p>
</li>
<li><p>访问某个类或者接口的<strong>静态变量</strong>，或者对该静态变量赋值</p>
</li>
<li><p>调用类的静态方法</p>
</li>
<li><p>反射</p>
</li>
<li><p>初始化一个类的子类（子类被创建的时候，<strong>所有的父类</strong>都会被创建）</p>
</li>
<li><p>Java虚拟机启动时被标名为启动类的类</p>
</li>
<li><p>动态语言支持（从jdk1.7开始支持）</p>
</li>
</ul>
<h3 id="被动使用"><a href="#被动使用" class="headerlink" title="被动使用"></a>被动使用</h3><p>除了上述七种情况，其他的所有情况都是类的<strong>被动使用</strong>，也就不会导致类的初始化。</p>
<h3 id="加载-class文件的方式"><a href="#加载-class文件的方式" class="headerlink" title="加载.class文件的方式"></a>加载<code>.class</code>文件的方式</h3><p>由于JVM规范并没有规定我们一定要从哪里加载这些<code>.class</code>文件，所以我们甚至可以加载不在本地的文件。这也正是为什么我们可以往我们的项目中添加jar包，也正是<code>Spring</code>框架中的<code>Maven</code>如此好用的原因。</p>
<p>所以有很多种方法可以加载：</p>
<ul>
<li><p>从本地系统中直接加载</p>
</li>
<li><p>通过网络下载.class文件</p>
</li>
<li><p>从zip、jar等归档文件中加载.class文件</p>
</li>
<li><p>从专有数据库中提取.class文件（用的极少）</p>
</li>
<li><p><strong>将Java源文件动态编译为.class文件</strong></p>
<ul>
<li><p>动态代理</p>
</li>
<li><p>jsp在运行期间会被转换成servlet，最终会被编译成.class文件</p>
</li>
</ul>
</li>
</ul>
<h2 id="应当注意的点"><a href="#应当注意的点" class="headerlink" title="应当注意的点"></a>应当注意的点</h2><ul>
<li><p>主动使用</p>
<ul>
<li><p><strong>对于静态字段来说，只有直接定义了该字段的类才会被初始化</strong></p>
<p>也就是说子类如果是从父类继承得到了静态变量而不是直接在子类内部定义的话，调用子类继承而得的静态变量时子类不会被初始化。</p>
</li>
<li><p><strong>当一个类在初始化时，要求其父类全部都初始化完毕才开始执行初始化</strong></p>
</li>
</ul>
</li>
</ul>
<p>所以，<code>Java</code>在实际运行中将会占用非常大的内存，这对于吞吐量极大的项目来说并不是一个好的选择，这也正是为什么腾讯和<code>bilibili</code>都正在逐渐使用<code>Go</code>重写整个系统。</p>
<h2 id="2020年11月21日更新"><a href="#2020年11月21日更新" class="headerlink" title="2020年11月21日更新"></a>2020年11月21日更新</h2><p>即使<code>Java</code>依然在性能上有着无法反驳的劣势，却在生态上有着无可撼动的地位。基于<code>Spring Cloud</code>的微服务框架能够集成<code>RabbitMQ</code>、<code>Redis</code>、<code>Zuul</code>、<code>Consul</code>等一切企业级信息管理框架所需要的内容，再加上基于<code>Spring Boot</code>的模块可以使用<code>yml</code>轻松集成，如此强大的生态已经成为了<code>Java</code>立于不败之地的重要因素。不仅如此，在面对海量的并发控制和请求处理的时候，可以<strong>使用非常多的服务器并联处理</strong>，做到了物理意义上的“<strong>三个臭皮匠，顶个诸葛亮</strong>”。这也是为什么<code>Java</code>依然能够在运行内存占用非常高的情况下依然保持这么高的支持率的原因之一。也正因为高支持率，才有了强大的社区和丰富的库。这就是一个良性循环了。</p>
<p>当然，随着微服务、<code>RPC</code>协议、<code>RESTful</code>接口规范等的提出，单个模块中使用什么语言逐渐变得不再重要了。只对外暴露输入和输出接口，屏蔽了中间过程的一切实现，已经成为了现在开发的主流。每个模块是选择开发效率更高的语言，或者是选择执行效率更高的语言，就看每个公司的追求了。所以，也无所谓<code>Java</code>还是<code>Go</code>的抉择，只要适合该企业，并且该企业有足够的资金维护该系统，那么就是合适的。</p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>代码滞销，救救码农</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/pay/wechatpay.png" alt="sakebow 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/pay/alipay.jpg" alt="sakebow 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    sakebow
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://sakebow.github.io/2020/02/06/Java/JVM/JVM%E7%B1%BB%E5%8A%A0%E8%BD%BD%E5%99%A8/" title="JVM类加载器">https://sakebow.github.io/2020/02/06/Java/JVM/JVM%E7%B1%BB%E5%8A%A0%E8%BD%BD%E5%99%A8/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/JVM/" rel="tag"> <i class="fa fa-tag"></i> JVM</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2020/02/06/Java/JVM/JVM%E5%B0%8F%E5%B7%A5%E5%85%B7/" rel="next" title="JVM小工具简介">
                <i class="fa fa-chevron-left"></i> JVM小工具简介
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2020/02/23/Java/%E9%9D%A2%E8%AF%95%E5%B8%B8%E8%80%83/HashMap%E8%AF%A6%E7%BB%86%E6%8E%A2%E7%A9%B6/" rel="prev" title="HashMap详细探究">
                HashMap详细探究 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      
        <div onclick="showGitment()" id="gitment-display-button">显示 Gitment 评论</div>
        <div id="gitment-container" style="display:none"></div>
      
    </div>
	<link rel="stylesheet" href="https://imsun.github.io/gitment/style/default.css">
    <script src="https://imsun.github.io/gitment/dist/gitment.browser.js"></script>
	<script>
      var gitment = new Gitment({
        id: '<%= page.date %>',
        owner: 'sakebow',
        repo: 'git@github.com:sakebow/sakebow.github.io.git',
        oauth: {
          client_id: '5c74c5e1b67e5a5adbdf',
          client_secret: '0d352353407a32cee695d8ac619108e725919c57',
        },
      });
      gitment.render('gitment-container');
    </script>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/icon/UN.png"
                alt="sakebow" />
            
              <p class="site-author-name" itemprop="name">sakebow</p>
              <p class="site-description motion-element" itemprop="description">哪怕是狗也不想随随便便放弃看到的骨头</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/%7C%7C%20archive">
              
                  <span class="site-state-item-count">70</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">21</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/sakebow" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:sakebowljx@gmail.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://plus.google.com/sakebow" target="_blank" title="Google">
                      
                        <i class="fa fa-fw fa-google"></i>Google</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://twitter.com/sakebow" target="_blank" title="Twitter">
                      
                        <i class="fa fa-fw fa-twitter"></i>Twitter</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                Links
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://github.com/sakebow" title="Sakebow的GitHub" target="_blank">Sakebow的GitHub</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.appgofast.com" title="我喜欢的VPN" target="_blank">我喜欢的VPN</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#导读"><span class="nav-number">1.</span> <span class="nav-text">导读</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#导读的解读"><span class="nav-number">2.</span> <span class="nav-text">导读的解读</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#类加载器深入剖析"><span class="nav-number">3.</span> <span class="nav-text">类加载器深入剖析</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Java虚拟机结束生命周期的时机"><span class="nav-number">3.1.</span> <span class="nav-text">Java虚拟机结束生命周期的时机</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#加载"><span class="nav-number">3.2.</span> <span class="nav-text">加载</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#链接"><span class="nav-number">3.3.</span> <span class="nav-text">链接</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#初始化"><span class="nav-number">3.4.</span> <span class="nav-text">初始化</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#使用"><span class="nav-number">3.5.</span> <span class="nav-text">使用</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#卸载"><span class="nav-number">3.6.</span> <span class="nav-text">卸载</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Java程序对类的使用方式"><span class="nav-number">4.</span> <span class="nav-text">Java程序对类的使用方式</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#主动使用"><span class="nav-number">4.1.</span> <span class="nav-text">主动使用</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#被动使用"><span class="nav-number">4.2.</span> <span class="nav-text">被动使用</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#加载-class文件的方式"><span class="nav-number">4.3.</span> <span class="nav-text">加载.class文件的方式</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#应当注意的点"><span class="nav-number">5.</span> <span class="nav-text">应当注意的点</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2020年11月21日更新"><span class="nav-number">6.</span> <span class="nav-text">2020年11月21日更新</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Sakebow</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        
<div class="busuanzi-count">
  <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    

    
      <div id="needsharebutton-float">
        <span class="btn">
          <i class="fa fa-share-alt" aria-hidden="true"></i>
        </span>
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  







<!-- LOCAL: You can save these files to your site and update links -->
    
        
        <link rel="stylesheet" href="https://aimingoo.github.io/gitmint/style/default.css">
        <script src="https://aimingoo.github.io/gitmint/dist/gitmint.browser.js"></script>
    
<!-- END LOCAL -->

    

    
      <script type="text/javascript">
      function renderGitment(){
        var gitment = new Gitmint({
            id: window.location.pathname, 
            owner: 'sakebow',
            repo: 'git@github.com:sakebow/sakebow.github.io.git',
            
            lang: "" || navigator.language || navigator.systemLanguage || navigator.userLanguage,
            
            oauth: {
            
            
                client_secret: '0d352353407a32cee695d8ac619108e725919c57',
            
                client_id: '5c74c5e1b67e5a5adbdf'
            }});
        gitment.render('gitment-container');
      }

      
      function showGitment(){
        document.getElementById("gitment-display-button").style.display = "none";
        document.getElementById("gitment-container").style.display = "block";
        renderGitment();
      }
      
      </script>
    







  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  
  
  <link rel="stylesheet" href="/lib/needsharebutton/needsharebutton.css">

  
  
  <script src="/lib/needsharebutton/needsharebutton.js"></script>

  <script>
    
    
      flOptions = {};
      
          flOptions.iconStyle = "box";
      
          flOptions.boxForm = "horizontal";
      
          flOptions.position = "middleRight";
      
          flOptions.networks = "Weibo,Douban,QQZone,Twitter,Facebook";
      
      new needShareButton('#needsharebutton-float', flOptions);
    
  </script>

  

  
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="https://cdn.bootcss.com/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


  

  
 
</body>
</html>
